import app from './common.js'
import ApiSignUtils from './ApiSignUtils.js';

const buildFullUrl = (url, data) => {
	if (!data || Object.keys(data).length === 0) return app.apiHost + url;

	// 手动构建get拼接参数字符串
	const params = Object.keys(data)
		.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
		.join('&');

	return `${app.apiHost}${url}?${params}`;
}

// 添加签名头拦截器[1,2](@ref)
const addSignatureHeaders = (headers) => {
	const signInfo = ApiSignUtils.generateSignature();

	return {
		...headers,
		'X-S-Str1': signInfo.str1,
		'X-S-Str2': signInfo.str2,
		'X-S-Str3': signInfo.str3,
		'X-S': signInfo.sign,
		'Timestamp': signInfo.tmp
	};
}

// 引入必要的API
const toast = (message) => {
	uni.showToast({
		title: message,
		icon: 'none',
	});
};

export const request = (options) => {
	//过滤data空参
	const filteredData = options.data ?
		Object.entries(options.data).reduce((acc, [key, value]) => {
			if (value !== "" && value !== null && value !== undefined) {
				acc[key] = value;
			}
			return acc;
		}, {}) : {};


	//添加固定data
	const mergedData = {
		platform: 1,
		...filteredData
	};

	const isGet = options.method?.toUpperCase() === 'GET';

	//get方法将data拼接到链接后边
	const finalUrl = isGet ? buildFullUrl(options.url, mergedData) : app.apiHost + options.url;

	//添加固定headers
	const token = app.getToken();
	const baseHeaders = options.header || {
		'Content-Type': 'application/json',
	};
	if (token) {
		baseHeaders['Authorization'] = `Bearer ${token}`; // 格式根据后端要求调整
	}
	// 用新变量接收签名后的 headers
	const signedHeaders = addSignatureHeaders(baseHeaders);
	console.log(
		"请求地址: " + finalUrl +
		"\n请求头部: " + JSON.stringify(signedHeaders, null, 2) +
		"\n请求参数: " + JSON.stringify(mergedData, null, 2)
	);

	return new Promise((resolve, reject) => {
		uni.request({
			url: finalUrl, // 拼接完整URL
			method: options.method || 'GET',
			data: isGet ? {} : mergedData,
			timeout: app.timeout,
			header: signedHeaders,
			success: (res) => {
				app.hideLoading();
				if (res.data.code !== 200) {
					console.log("请求失败", JSON.stringify(res, null, 2));

					// uni.navigateTo({
					// 	url: `/pages/rich-text/rich-text`,
					// 	success: (navRes) => {
					// 		navRes.eventChannel.emit('acceptDataFromOpenerPage', {
					// 			data: res.data // 发送完整数据
					// 		})
					// 	}
					// })

					if (res.data.code === 401) {
						app.removeLoginStorage();
						uni.navigateTo({
							url: '/pages/login-nav/login-nav'
						});
					} else if (res.data.code === -1100) {
						toast(res.data.msg || '请先进行实名');
					} else if (res.data.code === -1100) {
						toast(res.data.msg || '请先签署承诺书');
					} else if(res.data.code === 2100){
						resolve(res.data)
						return
					} else {
						toast(res.data.msg || '服务器繁忙，请稍后再试');
					}

					resolve(null);
				} else {
					console.log(
						"请求地址: " + finalUrl +
						"\n返回数据: " + JSON.stringify(res.data, null, 2)
					);
					resolve(res.data);
				}
			},
			fail: (err) => {
				app.hideLoading();
				console.log("请求失败", JSON.stringify(err, null, 2));
				toast('网络请求失败，请检查您的网络连接！')
				resolve(null);
			}
		});
	});
}